﻿using Best.HTTP.Shared.PlatformSupport.Memory;
using Best.WebSockets;
using System;

namespace Client.Hotfix
{
    public abstract class WSSession 
    {
        private WebSocket webSocket;
 
        public void InitSession(WebSocket ws)
        {
            webSocket = ws;
            webSocket.OnOpen += OnOpen;
            webSocket.OnClosed += OnClose;
            webSocket.OnMessage += OnMessage;
            webSocket.OnBinary += OnBinary;
        }

        private void OnOpen(WebSocket webSocket)
        {
            Connected();
        }
        private void OnBinary(WebSocket webSocket, BufferSegment data)
        {
            byte[] actualData = new byte[data.Count];
            Array.Copy(data.Data, data.Offset, actualData, 0, data.Count);
            ReceiveMessage(actualData);
        }

        private void OnMessage(WebSocket webSocket, string message)
        {
            ReceiveMessage(message);
        }
        private void OnClose(WebSocket webSocket, WebSocketStatusCodes code, string message)
        {
            DisConnected();
        }

        private void Connected()
        {
            OnConnected(true);
        }
        private void ReceiveMessage(byte[] buffer)
        {
            OnReceiveMessage(buffer);
        }
        private void ReceiveMessage(string message)
        {
            OnReceiveMessage(message);
        }
        private void DisConnected()
        {
            OnDisConnected();
        }
        protected abstract void OnConnected(bool connResult);
        protected abstract void OnReceiveMessage(byte[] buffer);
        protected abstract void OnReceiveMessage(string message);
        protected abstract void OnDisConnected();
        
        public bool Send(byte[] buffer)
        {
            try
            {
                webSocket.Send(buffer);
                return true;
            }
            catch (Exception ex)
            {
                this.LogYellow($"[ws] send error : {ex.Message}");
                return false;
            }
          
        }

        public bool Send(string message)
        {
            try
            {
                webSocket.Send(message);
                return true;
            }
            catch (Exception ex)
            {
                this.LogYellow($"[ws] send error : {ex.Message}");
                return false;
            }
        }

        public void CloseSession()
        {
            if (webSocket != null)
            {
                webSocket.OnOpen -= OnOpen;
                webSocket.OnClosed -= OnClose;
                webSocket.OnMessage -= OnMessage;
                webSocket.OnBinary -= OnBinary;
            }
        }
    }

}
